function fetchAdInvoice(link, skip) {
  openUrlAndExecScript(link, 'apps/fetch_ad_invoice/content.js', async data => {
    console.log(data)
    for (let i = skip + 1; i <= data.maxInvoiceIdNum; i++) {
      let url = `${data.baseURL}${i}`;
      let pageDetail = await getAdInvoiceDeatil(url);
      console.log(`开始上传：${data.invoiceKey}-${i}`)
      await uploadInvoice(pageDetail);
    }
  })
}

async function fetchAdInvoiceSchedule() {
  await sleep(Math.random() * 100 * 1000)
  let config = await getConfig()
  let stores = config.store.split('|')

  const adConfigUrl = 'https://api.miraazzurra.com/amazon/google_sheet/content?spreadsheetId=1LlK04ynKvQ8VGgx3wHkj6Xzmv_Ta9Ts-ahgj_RhrZzY&sheetName=店铺信息'
  const adConfig = await fetch(adConfigUrl).then(response => response.json())

  let sites = adConfig.filter(r => r[5].toString().trim() != '').filter(r => stores.includes(r[0]))

  for (let site of sites) {
    fetchAdInvoice(site[5], parseInt(site[7]))
    await sleep(30000)
  }
}

async function getAdInvoiceDeatil(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.text();
    return data;
  } 
  catch (error) {
    console.error('There was a problem with the fetch operation:', error);
    throw error
  }
}

async function uploadInvoice(detail) {
  const uploadUrl = 'https://api.miraazzurra.com/amazon/ad/invoice';
  let retryTime = 0;
  while (retryTime < 3) {
    try {
      await post(uploadUrl, { detail });
      retryTime = 4; // 成功后退出循环
    } catch (error) {
      retryTime++;
      if (retryTime >= 3) {
        console.log('上传 invoice 信息失败')
        throw error
      }
    }
  }
}
